package ru.housewife.service.wares;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.cache.CacheManager;
import ru.housewife.form.WaresGroupForm;
import ru.housewife.model.WaresGroup;

import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class AddNewWaresGroup implements HibernateAction<Boolean> {

    private CacheManager cacheManager = CacheManager.getInstance();

    private WaresGroupForm waresGroupForm;

    public AddNewWaresGroup(WaresGroupForm waresGroupForm) {
        this.waresGroupForm = waresGroupForm;
    }

    @Override
    public Boolean execute(Session session) {
        Query q = session.createQuery("select wg from WaresGroup wg where lower(wg.name) = :name");
        q.setString("name", waresGroupForm.getName().toLowerCase());
        List lst = q.list();
        if (lst != null && lst.size() > 0) {
            return false;
        }

        WaresGroup parentGroup = null;
        if (waresGroupForm.getParent() != null) {
            parentGroup = (WaresGroup) session.get(WaresGroup.class, waresGroupForm.getParent().getId());
            if (parentGroup == null) {
                return false;
            }
        }

        WaresGroup group = new WaresGroup();
        group.setName(waresGroupForm.getName());
        group.setParent(parentGroup);

        session.save(group);
        waresGroupForm.setId(group.getId());

        cacheManager.putWaresGroupForm(waresGroupForm);
        
        return true;
    }
}
